<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

/**
 *
 * @author "Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>"
 *
 */
class MDB2_ReverseEntityDefinition extends EntityDefinition
{

  /**
   * Table name
   *
   * @var string
   */
  protected $table;

  /**
   * Table's fields definitions
   *
   * @var array
   */
  protected $fields = array();

  /**
   * Primary key field(s)
   *
   * @var string|array
   */
  protected $pKey;

  /**
   * Constructor.
   *
   * @param array|IDictionary $params
   * @return void
   */
  public function __construct($db, $table)
  {
    $db->loadModule('Reverse', null, true);

    $params = array(
      'table' => $table, 'fields' => array()
    );

    $fields = $db->tableInfo($table);
    MDB2_DAO::validate($fields);

    foreach ($fields as $field) {
      $field['type'] = $this->translateType(sy_get_param($field, 'type'));

      $params['fields'][sy_get_param($field, 'name')] = array(
        sy_get_param($field, 'name'), sy_get_param($field, 'type'),
        array(
          'auto_increment' => sy_get_param($field, 'autoincrement'),
          'default' => sy_get_param($field, 'default'), 'length' => sy_get_param($field, 'length'),
          'name' => sy_get_param($field, 'name'), 'not_null' => sy_get_param($field, 'notnull'),
          'primary_key' => strpos(sy_get_param($field, 'flags'), 'primary_key') !== false,
          'unsigned' => sy_get_param($field, 'unsigned')
        )
      );
    }

    parent::__construct($params);
  }

  public function translateType($type)
  {
    $_type = $type;

    switch ($type) {
      case 'varchar' :
        $_type = 'text';
        break;
    }

    return $_type;
  }

}

?>